package cn.com.wangluotongxin.netty.event;

import cn.com.wangluotongxin.admin.netty.pojo.MessageInfo;
import cn.com.wangluotongxin.netty.cache.NettyChannelCacheUtil;
import cn.com.wangluotongxin.netty.pojo.ChannelPojo;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

@Component
public class SendMessageEventHandler implements ApplicationListener<SendMessageEvent> {


    @Override
    public void onApplicationEvent(SendMessageEvent event) {
        MessageInfo info = event.getMessageInfo();
        if(info == null) return;
        if(StrUtil.isBlank(info.getChannelId())) return;
        if(info.getData() == null || info.getData().isEmpty()) return;
        ChannelPojo pojo = NettyChannelCacheUtil.get(info.getChannelId());
        Channel channel = pojo.getChannel();
        if(channel == null) return;
        channel.writeAndFlush(new TextWebSocketFrame(info.getData().toJSONString()));
    }
}
